package com.mate.cloud.lottery.controller;


import com.mate.cloud.common.response.BaseResponse;
import com.mate.cloud.common.web.controller.AdminBaseController;
import com.mate.cloud.core.util.WebUtil;
import com.mate.cloud.lottery.constants.LotteryExceptionCodeEnum;
import com.mate.cloud.lottery.constants.RedisKeyManager;
import com.mate.cloud.lottery.converter.LotteryConverter;
import com.mate.cloud.lottery.domain.vo.LotteryItemVO;
import com.mate.cloud.lottery.dto.DoDrawDTO;
import com.mate.cloud.lottery.exception.RewardException;
import com.mate.cloud.lottery.service.ILotteryService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MI
 * @since 2025-01-24
 */
@Slf4j
@Controller
@RequestMapping("/lottery")
public class LotteryController extends AdminBaseController {

    @Autowired
    ILotteryService lotteryService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    LotteryConverter lotteryConverter;

    @GetMapping("/{id}")
    public BaseResponse<LotteryItemVO> doDraw(@PathVariable("id")Integer id, HttpServletRequest request){
        String accountIp = WebUtil.getIP(request);
        log.info("begin LotteryController.doDraw,access user {}, lotteryId,{}:",accountIp,id);
//        throw new RewardException(LotteryExceptionCodeEnum.REQUEST_PARAM_NOT_VALID.getCode());
        try {
            checkDrawParams(id, accountIp);
            DoDrawDTO dto=new DoDrawDTO();
            dto.setAccountIp(accountIp);
            dto.setLotteryId(id);
            lotteryService.doDraw(dto);

            return successBodyResponse(lotteryConverter.dto2LotteryItemVo(dto));

        } finally {
            //清除占位标记
            redisTemplate.delete(RedisKeyManager.getDrawingRedisKey(accountIp));
        }
    }
    private void checkDrawParams(Integer id,String accountIp){
        if(null==id){
            throw new RewardException(LotteryExceptionCodeEnum.REQUEST_PARAM_NOT_VALID.getCode());
        }
        //采用setNx命令，判断当前用户上一次抽奖是否结束
        Boolean result=redisTemplate.opsForValue().setIfAbsent(RedisKeyManager.getDrawingRedisKey(accountIp),"1", 60, TimeUnit.SECONDS);
        //如果为false，说明上一次抽奖还未结束
        if(!result){
            throw new RewardException(LotteryExceptionCodeEnum.LOTTER_DRAWING.getCode());
        }
    }
}
